
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;

public class Leetcode48 {
    public int lengthOfLongestSubstring1(String s) {
        Queue<Character> queue = new LinkedList<>();
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            if (queue.contains(s.charAt(i))) {
                while (queue.contains(s.charAt(i))){
                    queue.poll();
                }
                queue.add(s.charAt(i));
                count = Math.max(count,queue.size());
            }else {
                queue.add(s.charAt(i));
                count = Math.max(count,queue.size());
            }
        }
        return count;
    }

    public int lengthOfLongestSubstring(String s){
        char[] chars = s.toCharArray();
        HashMap<Character, Integer> map = new HashMap<>();
        int[] dp=new int[2];
        dp[0] = 0;
        int max = 0;
        for (int i = 0; i < chars.length; i++) {
            if (map.containsKey(chars[i])){
                int distance = i - map.get(chars[i]);
                if (distance<=dp[i%2]) dp[(i+1)%2] = distance;
                else dp[(i+1)%2] = dp[i%2]+1;
            }else {
                dp[(i+1)%2] = dp[i%2]+1;
            }
            max = Math.max(max,dp[(i+1)%2]);
            map.put(chars[i],i);
        }
        return max;
    }

}
